# load and show an image with Pillow
from PIL import Image
#Image location
imgloc= '/home/jayanthikishore/Downloads/ML_classwork/Week5/Sydney_Opera_House.jpg'
#Image save location
saveloc = '/home/jayanthikishore/Downloads/'
# load the image
image = Image.open(imgloc)
# summarize some details about the image
print(image.format)
print(image.mode)
print(image.size)
# show the image
image.show()
image
import matplotlib.pyplot as plt
plt.imshow(image)
# load all images in a directory
from os import listdir
from matplotlib import image
# load all images in a directory
loaded_images = list()
for filename in listdir('/home/jayanthikishore/Downloads/images/'):
print(filename)
# load image
img_data = image.imread('/home/jayanthikishore/Downloads/images/'+filename)
# store loaded image
loaded_images.append(img_data)
print('> loaded %s %s' % (filename, img_data.shape))
# example of saving an image in another format
from PIL import Image
# load the image
image = Image.open(imgloc)
# save as PNG format
image.save(saveloc+'opera_house.png', format='PNG')
# load the image again and inspect the format
image2 = Image.open(saveloc+'opera_house.png')
print(image2.format)
# example of saving a grayscale version of a loaded image
from PIL import Image
# load the image
image = Image.open(imgloc)
# convert the image to grayscale
gs_image = image.convert(mode='L')
# save in jpeg format
gs_image.save(saveloc+'opera_house_grayscale.jpg')
# load the image again and show it
image2 = Image.open(saveloc+'opera_house_grayscale.jpg')
# show the image
image2.show()
# create a thumbnail of an image
from PIL import Image
# load the image
image = Image.open(imgloc)
# report the size of the image
print(image.size)
# create a thumbnail and preserve aspect ratio
image.thumbnail((600,600))
# report the size of the thumbnail
print(image.size)
image.show()
# create flipped versions of an image
from PIL import Image
from matplotlib import pyplot
# load image
image = Image.open(imgloc)
# horizontal flip
hoz_flip = image.transpose(Image.FLIP_LEFT_RIGHT)
# vertical flip
ver_flip = image.transpose(Image.FLIP_TOP_BOTTOM)
# plot all three images using matplotlib
pyplot.subplot(311)
pyplot.imshow(image)
pyplot.subplot(312)
pyplot.imshow(hoz_flip)
pyplot.subplot(313)
pyplot.imshow(ver_flip)
pyplot.show()
# create rotated versions of an image
from PIL import Image
from matplotlib import pyplot
# load image
image = Image.open(imgloc)
# plot original image
pyplot.subplot(311)
pyplot.imshow(image)
# rotate 45 degrees
pyplot.subplot(312)
pyplot.imshow(image.rotate(45))
# rotate 90 degrees
pyplot.subplot(313)
pyplot.imshow(image.rotate(90))
pyplot.show()
# example of cropping an image
from PIL import Image
# load image
image = Image.open(imgloc)
# create a cropped image
cropped = image.crop((100, 100, 200, 200))
# show cropped image
cropped.show()